<?php


namespace app\common\business;

use app\common\lib\Arr;
use app\common\lib\Key;
use think\Exception;
use think\facade\Cache;

class Cart extends BusBase
{
    /**
     * 添加购物车
     * @param $userId
     * @param $id
     * @param $num
     * @return false
     */
    public function insertRedis($userId, $id, $num){
        // id 获取商品数据
        $goodsSku = (new GoodsSku())->getNormalSkuAndGoods($id);
        if(!$goodsSku){
            return FALSE;
        }
        $data = [
            'title' => $goodsSku['goods']['title'],
            'image' => $goodsSku['goods']['recommend_image'],
            'num' => $num,
            'goods_id' => $goodsSku['goods']['id'],
            'create_time' => time()
        ];
        try {
        	// 先看看商品是否存在存在数量相加避免覆盖
            $get = Cache::hGet(Key::userCart($userId), $id);
            if($get){
                $get = json_decode($get, true);
                $data['num'] = $data['num'] + $get['num'];// 需要检查库存是否足够待完成
            }
            $res = Cache::hSet(Key::userCart($userId), $id, json_encode($data));
        } catch(Exception $e){
            return FALSE;
        }
        return $res;
    }

    /**
     * 购物车列表
     * @param $userId
     * @return array
     */
    public function lists($userId, $ids){
        try {
            if($ids){
                $ids = explode(",", $ids);// 不传递是获取购物车中所有数据，传递了获取购物车中选中的数据去支付
                // $ids = [100,101]; 模拟数据不存在时 返回值
                $res = Cache::hMget(Key::userCart($userId), $ids);// 获取指定id数据
                if(in_array(false, array_values($res))){
                    return [];
                }
            } else{
                $res = Cache::hGetAll(Key::userCart($userId));// 获取购物车中所有数据去支付 个人购物车不会有太多，也可以在添加购物车时限制数量或者过期时间
            }
        } catch (Exception $e){
            $res = [];
        }
        if(!$res){
            return [];
        }
        $result = [];
        $skuIds = array_keys($res);
        $skus = (new GoodsSku())->getNormalInIds($skuIds);
        $stocks = array_column($skus, "stock", "id");
        $skuIdPrice = array_column($skus, "price", "id");
        $skuIdSpecsValueIds = array_column($skus, "specs_value_ids", "id");
        $specsValues = (new SpecsValue())->dealSpecsValue($skuIdSpecsValueIds);
        foreach($res as $k => $v){
            $price = $skuIdPrice[$k] ?? 0;
            $v = json_decode($v, true);
            if($ids && $stocks[$k] && $stocks[$k] < $v["num"]){
                throw new Exception($v['title']."的商品库存不足");
            }
            $v['id'] = $k;
            $v['image'] = preg_match("/http:\/\//", $v['image']) ? $v['image'] : input('server.REQUEST_SCHEME') . '://' . request()->server('HTTP_HOST').$v['image'];
            $v['price'] = $price;
            $v['total_price'] = $price * $v["num"];
            $v['sku'] = $specsValues[$k] ?? "暂无规格";
            $result[] = $v;
        }
        // 将最后添加到购物车的商品排在前面
        if(!empty($result)){
            $result = Arr::arrSortByKey($result, 'create_time');
        }
        // 考虑如何分页
        return $result;
    }

    /**
     * 删除购物车
     * @param $userId
     * @param $id
     * @return false
     */
    public function deleteRedis($userId, $ids){
        if(!is_array($ids)){
            $ids = explode(",", $ids);
        }
        try {
            // PHP参数数组通过可变参数传递: ...是PHP提供的一个特性，可变参数
            $res = Cache::hDel(Key::userCart($userId), ...$ids);
        }catch(Exception $e){
            return FALSE;
        }
        return $res;
        // 删除所有购物车内容
    }

    public function updateRedis($userId, $id, $num){
        // 需要检查库存是否足够待完成
        try {
            $get = Cache::hGet(Key::userCart($userId), $id);
        } catch(Exception $e){
            return FALSE;
        }
        if($get){
            $get = json_decode($get, true);
            $get['num'] = $num;
        } else {
            throw new Exception("购物车中不存在该商品");
        }
        try {
            $res = Cache::hSet(Key::userCart($userId), $id, json_encode($get));
        } catch(Exception $e){
            return FALSE;
        }
        return $res;
    }

    /**
     * @param $userId
     * @return int
     */
    public function getCount($userId){
        try {
            $count = Cache::hLen(Key::userCart($userId));
        } catch(Exception $e){
            return 0;
        }
        return intval($count);
    }
}
